import React, { CSSProperties, useCallback, useLayoutEffect, useMemo, useState } from "react";
import { FormContext } from "./Context";
import { FormItem } from "./FormItem";

interface IFormProps {
    name?: string;
    id?: string;
    children?: any;
    className?: string;
    style?: CSSProperties;
    defaultValues?: any;
    form?: any;
    onSubmit?: (data: any) => void;
}

interface IFormTempData {
    data: any;
}

export const Form = ({ form, ...others }: IFormProps) => {
    const [ defaultValues ] = useState(others.defaultValues ?? form?.defaultValues);
    const [ formData ] = useState<IFormTempData>({
        data: {
            ...(defaultValues || {})
        }
    });
    const onSubmit = useCallback((event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        event.stopPropagation();
        typeof others.onSubmit === "function" && others.onSubmit(formData.data);
        return false;
    }, [others.onSubmit]);
    const formContext = useMemo(() => ({
        data: formData.data,
        defaultValues: defaultValues,
        setData: (data: any) => {
            formData.data = {
                ...formData.data,
                ...data
            };
        },
        set: (name: string, value: any) => {
            formData.data[name] = value;
        }
    }), [formData]);
    useLayoutEffect(() => {
        if(form) {
            form.formData = formData.data;
            form.current = formContext;
        }
    }, [formContext]);
    return (<form {...others} onSubmit={onSubmit}>
        <FormContext.Provider value={formContext}>
            {others.children}
        </FormContext.Provider>
    </form>);
}

Form.Item = FormItem;